package com.xyebank.ledger.main;

import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.scheduling.annotation.EnableAsync;

import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.io.File;

@Configuration
@ComponentScan(basePackages = {"com.xyebank.ledger"})
@SpringBootApplication
@EnableSwagger2
@ImportResource({ "classpath:META-INF/spring/spring-main.xml" })
@EnableAsync
public class APP {

	public static void main(String[] args) {
		ConfigurableApplicationContext context = SpringApplication.run(APP.class, args);
		monitor(context);
	}

	/**
	 * 文件夹监控
	 * @param context
	 */
	public static void monitor(final ConfigurableApplicationContext context) {
		String filePath = "/home/cq/";
		FileAlterationObserver fileAlterationObserver = new FileAlterationObserver(filePath);
		fileAlterationObserver.addListener(new FileAlterationListenerAdaptor() {

			@Override
			public void onStart(FileAlterationObserver observer) {
//				System.out.println("start on file");
				super.onStart(observer);
			}

			@Override
			public void onDirectoryDelete(File directory) {
//				System.out.println("delete file");
				super.onDirectoryDelete(directory);
			}

			@Override
			public void onDirectoryCreate(File directory) {
//				System.out.println("create file");
				super.onDirectoryCreate(directory);
			}

			@Override
			public void onDirectoryChange(File directory) {
//				System.out.println("change file");
				super.onDirectoryChange(directory);
			}

			@Override
			public void onFileCreate(File file) {
//				System.out.println("file create");
				super.onFileCreate(file);
			}

			@Override
			public void onFileDelete(File file) {
//				System.out.println("file delete");
				super.onFileDelete(file);
			}

			@Override
			public void onFileChange(File file) {
//				System.out.println("file change");
				super.onFileChange(file);
			}
		});
		FileAlterationMonitor fileAlterationMonitor =  new FileAlterationMonitor(10000);
		fileAlterationMonitor.addObserver(fileAlterationObserver);
		try {
			fileAlterationMonitor.start();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
